<?php

	function show_post($row) {
		if (isset($row['img_src'])) {
			show_post_image($row);
			return;
		}

		if (isset($row['text']) and $row['text']) {
			show_post_text($row);
			return;
		}

		if ($row['post_type'] == 'image') {
			show_post_image($row);
		} else {
			show_post_text($row);
		}
	}

	function show_post_image($row)
	{
		if (isset($row['img_src'])) $row['image_url'] = $row['img_src'];
		if (!isset($row['description'])) $row['description'] = null;
		if (!isset($row['title'])) $row['title'] = null;

		// Проверяем вес картинки
		require_once 'Zend/Http/Client.php';
		
		$defaultValue = 0;
		if (substr($row['image_url'], 0, 18) == 'http://apikabu.ru/') {
			$defaultValue = 0;
		}
		
		if (false !== strstr($row['image_url'], 'joyreactor.ru')) {
			$defaultValue = 14;
		}
		
		$img = "
		
<script type='text/javascript'>
$(function() {
	$( '#slider-vertical' ).slider({
		orientation: 'vertical',
		range: 'min',
		min: 0,
		max: 100,
		value: $defaultValue,
		change: function( event, ui ) { 
			px = -$('#amount').val();
			$('#image').css('margin-bottom', px); 
	
		},
		slide: function( event, ui ) {
			$( '#amount' ).val( ui.value );
		}
	});

	$( '#amount' ).val( $( '#slider-vertical' ).slider( 'value' ) );
	$( '#image' ).css('margin-bottom', -$('#amount').val());
});
</script>
		
<table border='0' width='100%'><tr><td width='30%'>&nbsp;</td><td align='center' width='20%'>
		<table border='0' width='100%'>
			<tr>
				<td width='85%' align='right'>
					<div style='display:block; overflow:hidden; background: none repeat scroll 0 0;'>
						<img id='image' src='{$row['image_url']}' class='mini' />
					</div>
				</td>
				<td width='15%' height='100%' style='' align='center'>

<div>&nbsp;</div>		
<div id='slider-container' style='text-align:center; margin-left:10px;display:none;'>

<p>
	<input type='text' id='amount' name='cut_px' style='border:0; color:#f6931f; font-weight:bold;' />
</p>

<div id='slider-vertical' style='height: 300px;'></div>

</div>
				</td>
			</tr>
		</table>
</td><td width='30%'>&nbsp;</td></tr></table>		
";
		$lengthKb = null;
		try {
			$client = new Zend_Http_Client();
			//var_dump($row['image_url']);die();
			$client->setUri($row['image_url']);
			$client->setMethod('HEAD');
			$response = $client->request();
			$length = $response->getHeader('Content-length');
			$lengthKb = round($length/1024);
		} catch (Zend_Exception $e) {
			//$img = "<p><b>Картинки нет!</b><br />{$e->getMessage()}<br />{$row['image_url']}</p>";
		}
		
		if ($lengthKb > 500) {
			$img = addslashes($img);
			echo "<script type='text/javascript'>
			function show_big_image(self) {
				$(self).parent().html('<img id=\'image\' src=\'{$row['image_url']}\' class=\'mini\' />');
			}
			</script>";
			
			$img = "<p>Картинка слишком большая, весит {$lengthKb}Kb, <a href='#' onClick='show_big_image(this);'>все-равно показать</a>.</p>";
		}
			
		

		echo "<div><form class='report_form' method='post' id='{$row['id']}'>";
		echo "<a href='?cropper=1&id={$row['id']}'>cropper (beta)</a>";
		echo "<p><a class='url' href='{$row['url']}'>{$row['url']}</a></p>";
		$x = ucfirst(addslashes(trim($row['title'])));
		$lastSymb = substr($x, -1);
		if (($lastSymb != '.') and ($lastSymb != '!') and ($lastSymb != '?') and ($lastSymb != ')')) {
			$x .= '.';
		}
		
		echo "<h4 id='title' copy='$x'><span id='text-for-copy'>{$row['title']}</span> ({$row['rating']})</h4>";
		echo "<h5>{$row['description']}</h5>";
		//echo "<p size='-1'>{$row['url']}</p>";
		//echo "<p size='-1'>{$row['created']}</p>";
		echo $img;
		echo "<input type='hidden' name='url' value='{$row['image_url']}' />";
		echo "<input type='hidden' name='id' value='{$row['id']}' />";
		//echo "<div class='textarea'>Скопировать из названия ->";
		echo "<p><a id='text-copy' style='font-size: 10px;' href='#'>Скопировать из описания</a><br />
		<textarea id='additional' class='additional' title='Дополнительное описание к картинке' name='image_text'></textarea></p>";
		//echo "<p>Отрезать вотермарк 9gag? <input type='checkbox' name='cut_9gag' value='1' /></p>";
		echo "<input class='submit' type='submit' value='repost' />";
		echo "<input class='delete' type='submit' name='delete' value='delete' />";
		//echo "<input type='hidden' id='delete_{$row['id']}' name='is_delete' value='0' />";
		echo "</form></div>";
		echo "<br /><br />";
	}

	function show_post_text($row)
	{
		$text = str_replace("<br/>", "\n", $row['text']);
		$text = strip_tags($text);

		$title = null;
		if (isset($row['title'])) {
			$title = $row['title'];
		} else {
			$title = $row['ext_id'] . ' от ' . $row['add_date'];
		}

		$url = null;
		if (isset($row['url'])) {
			$url = $row['url'];
		} else {
			$url = 'http://bash.org.ru/quote/' . $row['ext_id'];
		}

		$description = null;
		if (isset($row['description'])) {
			$description = $row['description'];
		}

		echo "<form method='post' class='report_form' id='{$row['id']}'>";
		echo "<p><a class='url' href='{$url}'>{$url}</a></p>";
		echo "<h4>{$title} ({$row['rating']})</h4>";
		echo "<h5>{$description}</h5>";
		//echo "<p size='-1'>{$row['url']}</p>";
		//echo "<p size='-1'>{$row['created']}</p>";
		//echo "<p>Текст для репоста:</p>";
		echo "<p><textarea name='text' class='text'>{$text}</textarea></p>";
		echo "<input type='hidden' name='id' value='{$row['id']}' />";
		echo "<input class='submit' type='submit' value='repost' />";
		echo "<input class='delete' type='submit' name='delete' value='delete' />";
		//echo "<input type='hidden' id='delete_{$row['id']}' name='is_delete' value='0' />";
		echo "</form>";
	}

	// Считаем количество записей в таблицах, чтобы показать это в разделах
	$q = "select count(*) from pikabu where (post_type='text' or post_type='image') and vk_reposted = 0 and deleted = 0";
	$q2 = "select count(*) from pikabu where  (post_type='text' or post_type='image') and vk_reposted = 0 and deleted = 0 and rating > 50";
	$r = mysql_query($q);
	$r2 = mysql_query($q2);
	$error = mysql_error();
	if ($error) die($error);
	$x = mysql_fetch_row($r);
	$x2 = mysql_fetch_row($r2);
	$pikabu_count = "$x2[0]/$x[0]";
	
	$q = "select count(*) from joy where vk_reposted = 0 and deleted = 0";
	$r = mysql_query($q);
	$x = mysql_fetch_row($r);
	$joy_count = $x[0];

	$q = "select count(*) from bash where vk_reposted = 0 and deleted = 0";
	$r = mysql_query($q);
	$x = mysql_fetch_row($r);
	$bash_count = $x[0];
?>

<html>
<head>
	<title>Re: Pikabu</title>
	<script type='text/javascript' src='/ctl/static/jquery.js'></script>
	<script type='text/javascript' src='/ctl/static/jquery.form.js'></script>
	<script type='text/javascript' src='/ctl/static/form-default.js'></script>
	<script type='text/javascript' src='/ctl/static/img-click.js'></script>
	<script type='text/javascript' src='/ctl/static/php.js'></script>
	<script type='text/javascript' src='/ctl/static/text-copy.js'></script>
	<script type='text/javascript' src='/ctl/static/jquery-ui-1.8.17.custom.min.js'></script>
	<link rel="stylesheet" type="text/css" href="/ctl/static/style.css" />
	<link rel="stylesheet" type="text/css" href="/ctl/static/jquery-ui-1.8.17.custom.css" />
</head>
<body>
<table width='100%' height='100%'>
	<tr width='100%'>
		<td width='10%' height='25' align='center' valign='center' style='border-right: 1px solid black;'>
			<a href='/ctl/pikabu/'>Pikabu (<span id='pikabu_count'><?php echo $pikabu_count; ?></span>)</a>
		</td>
		<td width='10%' height='25' align='center' valign='center' style='border-right: 1px solid black;'>
			<a href='/ctl/joy/'>JoyReactor (<span id='joy-count'><?php echo $joy_count; ?></span>)</a>
		</td>
		<td width='10%' height='25' align='center' valign='center' style='border-right: 1px solid black;'>
			<a href='/ctl/bash/'>Bash (<span id='joy-count'><?php echo $bash_count; ?></span>)</a>
		</td>
		<td width='20%' height='25' align='center' valign='center' style='border-right: 1px solid black;'>
			<a href='http://vk.com/cat_vs_sad'>Котики против Печальки</a><br />
			<a href='http://vk.com/thebestjokes'>The Best Jokes</a>
		</td>
		<td width='20%' height='25' align='center' valign='center' style='border-right: 1px solid black;'>
			Мы работаем с группой:<br /><form method='post'>
			<select name='select_group'>
				<option value='33375244' <?php if ($config['groupId'] == 33375244) echo 'selected="selected"'; ?>>Котики против 
печальки</option>
				<option value='33342326' <?php if ($config['groupId'] == 33342326) echo 'selected="selected"'; ?>>The Best Jokes</option>
			</select>
			<input type='submit' name='change_group' value='Сменить' />
			</form>
		</td>
		<td width='20%' height='25' align='right' valign='center'>
			Привет, <?php echo $config['first_name']; ?> | <a href='/ctl/?exit'>Выйти</a>
		</td>
	</tr>
<?php
$message = message();
?>
	<tr>
		<td width='100%' height='<?php if ($message) echo "25"; else echo "0"; ?>' style='border-top: 1px solid black; font-weight: bold; <?php if 
($message) echo "background-color: #D6FFD6;"; ?>' colspan='6' align='center' valign='center' id='message'> 
			<?php echo $message; ?>
		</td>
	</tr>
	<tr>
		<td width='100%' height='100%' style='border-top: 1px solid black;' colspan='6' align='center' valign='center' id='post'>
<?php

$onlyPikabu = null;
if ($config['page'] == 'pikabu') {
	$onlyPikabu = "and (post_type = 'text' or post_type='image') ";
}
	
	$fivemin = strtotime("-1 min");
	$fivemin = date("Y-m-d H:i:s", $fivemin);
	$order = 'rating desc';
	if ($config['page'] == 'koto') {
		$order = 'rand()';
	}
	$query = "select * from {$config['page']} where vk_reposted = 0 $onlyPikabu and deleted = 0 and modified < '$fivemin' order by $order limit 1";
	//echo $query;
	$result = mysql_query($query) or die(mysql_error());

	$q = "select * from user where ext_id = {$config['user_id']}";
	$r = mysql_query($q);
	$userRow = mysql_fetch_assoc($r);
	$repost = $userRow['repost_count'];
	$delete = $userRow['delete_count'];
	if ($delete == 0) $delete = 1;
	$match = $repost/$delete;
	$percent = round($match * 100);
	$additionalTipses = array();
	if ($match < 0.1) {
		$additionalTipses = array(
			"<b size='+1'>Ты репостишь в среднем $percent% записей. Оптимальное значение должно быть на уровне 10%, будь добрее!</b>",
		);
	}

	$tipses = array(
		'Вводи описание с большой буквы.',
		'Соблюдай пунктуацию, ставь точку в конце предложения.',
		'Ставь лайки всем постам в <a href="http://vkontakte.ru/cat_vs_sad">группе</a>.',
		'Будь клёвым!',
		'Не вводи описание, если оно не в тему.',
		'Если кликнуть на картинку - она станет оригинального размера.',
		'Pikabu (10/100) означает что всего есть 100 постов, и 10 с большим рейтингом.',
		"Ты зарепостил $repost и удалил $delete записей.",
		"При обновлении страницы пост не исчезает, он покажется снова через минуту.",
		"Разделы joyreactor.ru & bash.org.ru заработали!",
		"Нововведение: Вотермарки снизу можно отрезать у полноразмерных картинок. Кликайте по картинке и появится слайдер.",
		"Нововведение: Кнопка <i>Скопировать из описания</i> над полем ввода, используйте с умом, иногда можно придумать что-то более креативное... ;)",
	);

	$tipses = array_merge($tipses, $additionalTipses);

	while ($row = mysql_fetch_assoc($result)) {
		show_post($row);

		$rand = rand(0, count($tipses) - 1);
		$tip = $tipses[$rand];
		echo "<p class='tips'>$tip</p>";
		$newCount = $row['view_count'] + 1;
		mysql_query("update {$config['page']} set view_count = $newCount where id = {$row['id']}");
	}
?>
		</td>
	</tr>
</table>

